# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

from novel.dao import noveldao, authordao, categorydao, charpterdao
from novel.items import NovelItem, CharpterItem
from novel.utils.tool import itemtype


class NovelPipeline(object):

    def process_item(self, item, spider):
        return item


class NovelCSVPipeline(object):
    def process_item(self, item, spider):
            return item

class AuthorMySQLPipeline(NovelPipeline):

    @itemtype(NovelItem)
    def process_item(self, item, spider):
        author_row = authordao.findByNameAuthor(item['author'])
        # 没有作者记录
        if not author_row:
            authordao.insertAuthor(item['author'])
        return item

class NovelMySQLPipeline(NovelPipeline):


    @itemtype(NovelItem)
    def process_item(self, item, spider):

        if isinstance(item,NovelItem):

            author_row=authordao.findByNameAuthor(item['author'])

            #没有作者记录
            if not author_row:
                author_id=authordao.insertAuthor(item['author'])
            else:
                author_id=author_row[0]

            if not noveldao.findBySourceNovel(item['source']):
                #插入小说
                noveldao.insertNovel(item,author_id)
        return item  # 必须实现返回

class CategoryMYSQLPipeline(NovelPipeline):
    """
     类别处理
    """

    @itemtype(NovelItem)
    def process_item(self, item, spider):

        type_rows = categorydao.findAll()
        type_id=None
        for row in type_rows:
            if item['type'] in row[2]:
                type_id=row[0]
                break

        if type_id==None:
            type_id = categorydao.insertCategory(item['type'])


        novel=noveldao.findBySourceNovel(item['source'])
        if novel!=None:
            nid=novel[0]
            categorydao.insertNovelAndCategory(nid,type_id)
        return item


class CharpterMySQLPipeline(NovelPipeline):

    @itemtype(CharpterItem)
    def process_item(self, item, spider):
        charpterdao.insertmany(item['id'],item['chapter'])

        return item


class UpdataCharpterMySQLPipeline(object):

    @itemtype(CharpterItem)
    def process_item(self, item, spider):
        try:
            if item['no'] == None and item['id'] == None:
                return item
        except:
            return item

        charpterdao.insertCharpter(item)
        return item
